package com.yinxin.thread.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yinxin
 * @version 1.0
 * @Description:
 * @date 2022/5/116:11
 */
public class ThreadTest {

    private int j;
    private Lock Lock = new ReentrantLock();
    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();
        for (int i = 0; i < 2; i++) {
            new Thread(threadTest.new Adder()).start();
            new Thread(threadTest.new Subtractor()).start();
        }
    }

    //累减器
    private class Subtractor implements Runnable{
        @Override
        public void run() {
//            synchronized (ThreadTest.this){
//                System.out.println("j-- = " + j--);
//            }
            Lock.lock();
            try {
                System.out.println("j-- = " + j--);
            }finally {
                Lock.unlock();
            }
        }
    }

    //累加器
    private class Adder implements Runnable{
        @Override
        public void run() {
//            synchronized (ThreadTest.this){
//                System.out.println("j++ = " + j++);
//            }
            Lock.lock();
            try {
                System.out.println("j++ = " + j++);
            }finally {
                Lock.unlock();
            }
        }
    }
}
